<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/1/5
 * 描述:
 */

namespace app\result;

use app\model\order\Order;
use app\model\order\OrderGoods;
use app\model\order\OrderRefund;
use app\result\order\OrderResult;
use app\service\LockService;
use think\facade\Db;

class RefundResult extends BaseResult
{
    public function ready($user_id, $args = []): array
    {
        $order_sn = $args['order_sn'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        $model = new Order();
        $order = $model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id], 'order_pay_price,pay_price,order_sn,order_id,order_status')?->toArray();
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if (!in_array($order['order_status'], [1, 2, 3, 4])) {
            return self::error_return('订单状态不支持退款');
        }
        $goods = (new OrderGoods())->data_list_nopage(['order_id' => $order['order_id']], 'id,goods_name,goods_total_price as goods_price,goods_spec,goods_image');
        $reasons = [
            ['label' => '不想要了', 'value' => '不想要了'],
            ['label' => '超时不发货', 'value' => '超时不发货'],
            ['label' => '缺货', 'value' => '缺货'],
            ['label' => '协商一致', 'value' => '协商一致'],
            ['label' => '商品质量问题', 'value' => '商品质量问题'],
            ['label' => '未收到货', 'value' => '未收到货'],
            ['label' => '发票问题', 'value' => '发票问题'],
            ['label' => '商品描述不符', 'value' => '商品描述不符'],
            ['label' => '卖家发错货', 'value' => '卖家发错货'],
            ['label' => '其他', 'value' => '其他'],
        ];
        return self::success_return('success', [
            'reasons' => $reasons,
            'order_info' => $order,
            'goods_list' => $goods,
        ]);
    }

    public function save($user_id, $args = []): array
    {
        $order_sn = $args['order_sn'] ?? '';
        $reason = $args['reason'] ?? '';
        $remark = $args['remark'] ?? '';
        $images = $args['images'] ?? [];
        $refund_price = $args['refund_price'] ?? '';
        if (!$order_sn) {
            return self::error_return('请选择订单');
        }
        if (!$reason) {
            return self::error_return('请选择退款原因');
        }
        $model = new Order();
        $order = $model->data_get(['order_sn' => $order_sn, 'user_id' => $user_id], 'order_pay_price,pay_price,order_sn,order_id,order_status')?->toArray();
        if (!$order) {
            return self::error_return('订单不存在');
        }
        if (!in_array($order['order_status'], [1, 2, 3, 4])) {
            return self::error_return('订单状态不支持申请退款');
        } elseif ($order['order_status'] == 5) {
            return self::error_return('申请审核中');
        }
        if ($refund_price && $refund_price > $order['pay_price']) {
            return self::error_return('退款金额不能大于支付金额');
        }
        $lock = 'order_refund_' . $order['order_id'];
        if (!LockService::logck_by_second($lock, 5)) {
            return self::error_return('正在处理，请勿重复提交');
        }
        $baseData = [
            'order_status' => $order['order_status'],
            'order_id' => $order['order_id'],
            'order_sn' => $order['order_sn'],
            'user_id' => $user_id,
            'reason' => $reason,
            'remark' => $remark,
            'images' => join(',', $images),
            'status' => 0,
            'refund_price' => $refund_price ?: $order['pay_price'],//默认退款全部金额
        ];
        Db::startTrans();
        try {
            $res = (new OrderRefund())->data_add($baseData);
            if (!$res) {
                throw new \Exception('记录退款申请失败');
            }
            $res = (new Order())->data_update(['order_id' => $order['order_id']], ['order_status' => 5]);
            if (!$res) {
                throw new \Exception('更新订单状态失败');
            }
            OrderResult::add_order_log([
                'order_id' => $order['order_id'],
                'order_sn' => $order['order_sn'],
                'remark' => '申请退款',
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            LockService::unlock($lock);
            return self::error_return('保存失败:' . $e->getMessage());
        }
        Db::commit();
        return self::success_return('退款申请成功');

    }
}
